import 'dart:async';
import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jicaimao_flutter/entity/loginbean.dart';
import 'package:jicaimao_flutter/utils/api_address.dart';
import 'package:jicaimao_flutter/utils/http_utils.dart';
import 'package:jicaimao_flutter/utils/sp_key.dart';
import 'package:jicaimao_flutter/utils/sp_utils.dart';
import 'package:jicaimao_flutter/utils/string_utils.dart';
import 'package:jicaimao_flutter/widget/app_bar.dart';
import 'package:jicaimao_flutter/widget/forget_password_progress.dart';

class ForgetPasswordPage extends StatefulWidget {
  String pwd_state = "2";

  @override
  _ForgetPasswordPageState createState() => _ForgetPasswordPageState();

  ForgetPasswordPage(this.pwd_state);

}

class _ForgetPasswordPageState extends State<ForgetPasswordPage> {
  bool isGoNext1 = false;
  bool isGoNext2 = false;
  bool isGoNext3 = false;
  bool isClearShow = false;
  bool isClickGetCode = false;
  String sendCode = "";

  bool noShow1 = true;
  bool noShow2 = true;
  final phoneController = TextEditingController();
  final codeController = TextEditingController();
  final psw1Controller = TextEditingController();
  final psw2Controller = TextEditingController();

  String titleText = "";
  String pswText = "";
  String pswHint1 = "";
  String pswHint2 = "{msg: 密码修改成功, code: 200, result: {status: ok}, pageNumber: null, totalPages: null, pageSize: null}";
  String pswSuccessText = "";

  int progress = 0;

  String phone;
  String verificationCode;
  String psw1;
  String psw2;

  /// 倒计时的秒数，默认60秒。
  final int countdown = 60;

  /// 倒计时的计时器。
  Timer _timer;

  /// 当前倒计时的秒数。
  int _seconds;

  /// 当前墨水瓶（`InkWell`）的文本。
  String _verifyStr = '获取验证码';

  /**
   * 开启倒计时
   */
  countDown() {
    _startTimer();
    _verifyStr = '${_seconds}s';
    setState(() {});
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_seconds == 0) {
        _cancelTimer();
        _seconds = countdown;
//            inkWellStyle = _availableStyle;
        setState(() {});
        return;
      }
      _seconds--;
      _verifyStr = '${_seconds}s';
      setState(() {});
      if (_seconds == 0) {
        _verifyStr = '重新获取';
      }
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  @override
  void initState() {
    super.initState();
    _seconds = countdown;

    switch (widget.pwd_state) {
      case "0":
        titleText = "设置支付密码";
        pswText = "支付密码设置";
        pswHint1 = "设置支付密码(6位数字)";
        pswHint2 = "请再次输入支付密码";
        pswSuccessText = "支付密码设置成功";
        sendCode = "3";
        break;
      case "1":
        titleText = "修改支付密码";
        pswText = "修改支付密码流程";
        pswHint1 = "修改支付密码(6位数字)";
        pswHint2 = "请再次输入支付密码";
        pswSuccessText = "支付密码修改成功";
        sendCode = "4";
        break;
      case "2":
        sendCode = "2";
        titleText = "修改登录密码";
        pswText = "修改登录密码";
        pswHint1 = "请输入新的登录密码(6-18位数字和字母)";
        pswHint2 = "请再次输入登录密码";
        pswSuccessText = "登录密码修改成功";
        break;
    }
    print("sendCode:" + sendCode);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarNormal(titleText),
      body: new SingleChildScrollView(
        child: new ConstrainedBox(
          constraints: new BoxConstraints(
            minHeight: 120.0,
          ),
          child: Container(
            child: Column(children: <Widget>[
              Container(
                color: Color(0xFFF1F1F1),
                height: 40,
                padding: EdgeInsets.only(left: 20),
                width: double.infinity,
                alignment: Alignment.centerLeft,
                child: Text(
                  pswText,
                  style: TextStyle(fontSize: 16),
                ),
              ),
              ForgetPasswordProgress(progress: progress),
              Container(
                color: Color(0xfff1f1f1),
                height: 10,
              ),
              getBottom(),
            ]),
          ),
        ),
      ),
    );
  }

  ///第一步 校验手机号码 布局
  _phoneCheck() {
    return Column(
      children: <Widget>[
        _inputPhone(),
        Container(
          margin: EdgeInsets.only(left: 20, right: 20),
          height: 1,
          color: Color(0xffDCDCDC),
        ),
        _inputCode(),
        GestureDetector(
          onTap: _btnNextOne,
          child: Container(
              margin: EdgeInsets.only(top: 40, left: 20, right: 20),
              decoration: new BoxDecoration(
                  color: isGoNext1 ? Color(0xffad5afe) : Color(0xffD4d4d4),
                  borderRadius: BorderRadius.circular(3.0)),
              alignment: Alignment.center,
              height: 40,
              width: double.infinity,
              child: Text(
                "下一步",
                style: TextStyle(color: Colors.white),
              )),
        ),
      ],
    );
  }

  ///第二步 输入密码 布局
  _OnePsw() {
    return Column(
      children: <Widget>[
        _inputPassword1(),
        GestureDetector(
          onTap: _btnNextTwo,
          child: Container(
              margin: EdgeInsets.only(top: 40, left: 20, right: 20),
              decoration: new BoxDecoration(
                  color: isGoNext2 ? Color(0xffad5afe) : Color(0xffD4d4d4),
                  borderRadius: BorderRadius.circular(3.0)),
              alignment: Alignment.center,
              height: 40,
              width: double.infinity,
              child: Text(
                "下一步",
                style: TextStyle(color: Colors.white),
              )),
        ),
      ],
    );
  }

  ///第三步 确认密码 布局
  _OkPsw() {
    return Column(
      children: <Widget>[
        _inputPassword2(),
        GestureDetector(
          onTap: _btnNextThree,
          child: Container(
              margin: EdgeInsets.only(top: 40, left: 20, right: 20),
              decoration: new BoxDecoration(
                  color: isGoNext3 ? Color(0xffad5afe) : Color(0xffD4d4d4),
                  borderRadius: BorderRadius.circular(3.0)),
              alignment: Alignment.center,
              height: 40,
              width: double.infinity,
              child: Text(
                "下一步",
                style: TextStyle(color: Colors.white),
              )),
        ),
      ],
    );
    ;
  }

  ///第四步 修改成功 布局
  _forgetComplete() {
    return Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 40),
          alignment: Alignment.center,
          child: Image.asset('images/icon_success.png'),
        ),
        Container(
          margin: EdgeInsets.only(top: 20),
          alignment: Alignment.center,
          child: Text(pswSuccessText),
        )
      ],
    );
  }

  ///--------------------------------输入手机
  _inputPhone() {
    return Container(
        height: 40,
        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
        margin: EdgeInsets.fromLTRB(20, 40, 20, 0),
        color: Color(0xfff7f7f7),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: TextField(
                onChanged: setBtnState1,
                controller: phoneController,
                inputFormatters: [LengthLimitingTextInputFormatter(11)],
                maxLength: 11,
                maxLines: 1,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                    hasFloatingPlaceholder: false,
                    counterText: '',
                    border: InputBorder.none,
                    hintText: '请输入手机号',
                    disabledBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none),
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16.0,
                ),
              ),
            ),
            GestureDetector(
              child: Container(
                width: 40,
                height: 40,
                padding: EdgeInsets.fromLTRB(20, 10, 0, 10),
                child: Image.asset(isClearShow ? 'images/icon_error.png' : ''),
              ),
              onTap: () {
                phoneController.clear();
                setState(() {
                  isClearShow = !isClearShow;
                });
              },
            )
          ],
        ));
  }

  ///--------------------------------验证码
  _inputCode() {
    return Container(
      height: 40,
      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
      margin: EdgeInsets.only(right: 20, left: 20),
      color: Color(0xfff7f7f7),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: TextField(
              onChanged: setBtnState1,
              controller: codeController,
              inputFormatters: [LengthLimitingTextInputFormatter(11)],
              maxLength: 11,
              maxLines: 1,
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                  hasFloatingPlaceholder: false,
                  counterText: '',
                  border: InputBorder.none,
                  hintText: '请输入验证码',
                  disabledBorder: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none),
              style: TextStyle(
                color: Color(0xff666666),
                fontSize: 16.0,
              ),
            ),
          ),
          InkWell(
            child: Text(
              '$_verifyStr',
              style: TextStyle(color: Color(0xff6aa9ff)),
            ),
            onTap: _seconds == countdown ? _getCode : null,
          )
        ],
      ),
    );
  }

  ///--------------------------------输入密码
  _inputPassword1() {
    return Container(
        height: 40,
        margin: EdgeInsets.only(top: 40, left: 20, right: 20),
        padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
        color: Color(0xfff7f7f7),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: TextField(
                controller: psw1Controller,
                keyboardType: TextInputType.text,
                onChanged: (text) {
                  bool b2 = StringUtils.checkAccountMarkNmu(text);
                  bool isSixPwd = StringUtils.isSixPwd(text);
                  setState(() {
                    if ("0" == widget.pwd_state || "1" == widget.pwd_state) {
                      if (!isSixPwd) {
                        isGoNext2 = false;
                      } else {
                        isGoNext2 = true;
                      }
                    } else {
                      if (!b2) {
                        isGoNext2 = false;
                      } else {
                        isGoNext2 = true;
                      }
                    }
                  });
                },
                maxLines: 1,
                obscureText: noShow1,
                decoration: InputDecoration(
                    hasFloatingPlaceholder: false,
                    border: InputBorder.none,
                    hintText: pswHint1,
                    counterText: '',

                    ///限制最大长度后
                    disabledBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none),
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16.0,
                ),
              ),
            ),
            GestureDetector(
              child: Container(
                  width: 40,
                  height: 40,
                  padding: EdgeInsets.all(10),
                  child: Image.asset(
                      noShow1 ? 'images/ps_notsee.png' : 'images/ps_see.png')),
              onTap: () {
                setState(() {
                  noShow1 = !noShow1;
                });
              },
            )
          ],
        ));
  }

  ///--------------------------------确认密码
  _inputPassword2() {
    return Container(
        height: 40,
        margin: EdgeInsets.only(top: 40, right: 20, left: 20),
        padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
        color: Color(0xfff7f7f7),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: TextField(
                controller: psw2Controller,
                keyboardType: TextInputType.text,
                onChanged: (text) {
                  bool b2 = StringUtils.checkAccountMarkNmu(text);
                  bool isSixPwd = StringUtils.isSixPwd(text);
                  setState(() {
                    if ("0" == widget.pwd_state || "1" == widget.pwd_state) {
                      if (!isSixPwd) {
                        isGoNext3 = false;
                      } else {
                        isGoNext3 = true;
                      }
                    } else {
                      if (!b2) {
                        isGoNext3 = false;
                      } else {
                        isGoNext3 = true;
                      }
                    }
                  });
                },
                maxLines: 1,
                obscureText: noShow2,
                decoration: InputDecoration(
                    hasFloatingPlaceholder: false,
                    border: InputBorder.none,
                    hintText: pswHint2,
                    counterText: '',

                    ///限制最大长度后
                    disabledBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none),
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16.0,
                ),
              ),
            ),
            GestureDetector(
              child: Container(
                  width: 40,
                  height: 40,
                  padding: EdgeInsets.all(10),
                  child: Image.asset(
                      noShow2 ? 'images/ps_notsee.png' : 'images/ps_see.png')),
              onTap: () {
                setState(() {
                  noShow2 = !noShow2;
                });
              },
            )
          ],
        ));
  }

  ///--------------------------------设置第一个按钮状态
  setBtnState1(text) {
    String pNum = phoneController.text;
    String ver = codeController.text;

    if (pNum.isNotEmpty && RegexUtil.isMobileExact(pNum) && ver.isNotEmpty) {
      setState(() {
        isClearShow = text.length > 0;
        isGoNext1 = true;
      });
    } else {
      setState(() {
        isGoNext1 = false;
      });
    }
  }

  ///--------------------------------底部的布局选择
  getBottom() {
    switch (progress) {
      case 0:
        return _phoneCheck();
      case 1:
        return _OnePsw();
      case 2:
        return _OkPsw();
      case 3:
        return _forgetComplete();
    }
  }

  ///第一步确定按钮 校验手机号码
  _btnNextOne() {
    String pNum = phoneController.text;
    String ver = codeController.text;
    if (pNum.isEmpty) {
     showToast( "请输入手机号码");
      return;
    }
    if (!RegexUtil.isMobileExact(pNum)) {
      showToast(  "手机号格式不正确");
      return;
    }

    if (ver.isEmpty) {
      showToast( "请输入验证码");
      return;
    }

    if (!isClickGetCode) {
      showToast(  "请先获取验证码");
      return;
    }
    //校验验证码
    if ("0" == widget.pwd_state) {
      //设置支付密码的验证码校验
      _checkCode(pNum, ver, "3");
    } else if ("1" == widget.pwd_state) {
      //修改支付密码的验证码校验
      _checkCode(pNum, ver, "4");
    } else {
      //登录密码的验证码校验
      _checkCode(pNum, ver, "2");
    }
  }

  /// 获取验证码
  _getCode() {
    String pNum2 = phoneController.text;
//    print(pNum2+":"+sendCode);
    isClickGetCode = true;
    if (pNum2.isEmpty) {
      showToast(  "请输入手机号码");
      return;
    }
    if (!RegexUtil.isMobileExact(pNum2)) {
      showToast( "手机号格式不正确");
      return;
    }
    _sendCode(pNum2);
  }
  bool isReq = false;
  _sendCode(String PhoneNum) async {
     if(isReq)
       return;
     isReq = true;
    var data = {
      'codeType': sendCode,
      "mobile": PhoneNum,
    };
    var respone = await HttpUtil().post(NetAddress.getCode, data: data);
    print(respone);
    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
     showToast(  loginBean.msg);
    if (loginBean.code == "200") {
      countDown();
    } else {}
     isReq = false;
  }

  _checkCode(String phoneNmu, String phoneCode, String codeType) async {
    var data = {
      'codeType': sendCode,
      'mobile': phoneNmu,
      'verificationCode': phoneCode
    };
    var respone = await HttpUtil().post(NetAddress.checkCode, data: data);
    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
    if (loginBean.code == "200") {
      verificationCode = phoneCode;
      phone = phoneNmu;
      setState(() {
        progress = 1;
      });
    }
  }

  ///第二步确定按钮 输入密码
  _btnNextTwo() {
    String pPassWord = psw1Controller.text;
    if (pPassWord.isEmpty) {
      showToast(  "请输入密码");
      return;
    }
    if ("0" == widget.pwd_state || "1" == widget.pwd_state) {
      bool isSixPwd = StringUtils.isSixPwd(pPassWord);
      if (!isSixPwd) {
        showToast(  "密码为6位数字");
        return;
      }
    } else {
      bool b2 = StringUtils.checkAccountMarkNmu(pPassWord);
      if (!b2) {
        showToast( "密码为6-18位数字和字母");
        return;
      }
    }

    psw1 = pPassWord;
    setState(() {
      progress = 2;
    });
  }

  ///第三步确定按钮  确认密码
  _btnNextThree() {
    var pPassWord2 = psw2Controller.text;
    if (pPassWord2.isEmpty) {
      showToast( "请输入密码");
      return;
    }
    if (pPassWord2 != psw1) {
      showToast( "两次密码不一样");
      return;
    }
    if ("0" == widget.pwd_state || "1" == widget.pwd_state) {
      _setAndUpdatePayPwd(pPassWord2, verificationCode, phone);
    } else {
      _getModifyPassword(pPassWord2, verificationCode, phone);
    }
  }

  ///设置与修改支付密码
  _setAndUpdatePayPwd(String pwd, String code, String phoneNum) async {
    print("_setAndUpdatePayPwd");
    var data = {
      "userId": SpUtils.getString(SpKey.KEY_USER_ID),
      'codeType': sendCode,
      'mobile': phoneNum,
      "payPassword": pwd,
      'smsCode': code
    };
    var respone = await HttpUtil().post(NetAddress.setPayPassword, data: data);
    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
    showToast( loginBean.msg);
    if (loginBean.code == "200") {
      if ("0" == widget.pwd_state) {
        showToast( "设置支付密码成功");
      } else if ("1" == widget.pwd_state) {
        showToast(  "修改支付密码成功");
      }
      Navigator.pop(context);
    } else {
      showToast(  loginBean.msg);
    }
  }

  ///修改登录密码接口
  _getModifyPassword(String pwd, String code, String phoneNum) async {
    print("_getModifyPassword");
    var data = {
      "userId": "", //SpUtils.getString(SpKey.KEY_USER_ID),
      'codeType': sendCode,
      "password": pwd,
      'mobile': phoneNum,
      'verificationCode': code
    };
    var respone = await HttpUtil(type:ResponseType.PLAIN).post(NetAddress.modifyPassword, data: data);
//    print("这是一个什么：："+(respone as String));
//    var decode = json.decode(respone);
//
    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
    showToast(  loginBean.msg);
    if (loginBean.code == "200") {
      setState(() {
        progress = 3;
      });
    }
  }


  void showToast(String tipMsg) {
    Fluttertoast.showToast(
        msg: tipMsg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Colors.black87,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
